<template>
    <div class="notepad_manage_span">
        <table-span
            :current-page="tabelData.current"
            :page-size="tabelData.size"
            :total="tabelData.total"
            :isShowTool="false"
            :size-change="handleSizeChange" 
            :current-change="handleCurrentChange">
            <template v-slot:searchItem>
                <div class="search_item_fix_width">
                    <el-date-picker
                        v-model="dateInterval"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        size="default"
                        value-format="YYYY-MM-DD"
                        :clearable=true
                    />
                </div>
                <div class="search_item_span">
                    <el-select v-model="notepadCondition.type" placeholder="请选择消息类型"
                               size="default" clearable>
                        <el-option
                                v-for="item in parentList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="search_item_span">
                    <el-button icon="Search" size="default" type="primary" @click="searchData">查询</el-button>
                </div>
                <div class="search_item_span">
                    <el-button icon="Plus" size="default"
                        type="primary" :disabled="!(btOption.btSaveNotepad)"
                        @click="btInsertNotepad">新增消息</el-button>
                </div>
            </template>
            <template v-slot:searchTable>
                <el-table :data="tabelData.records" size="default" height="100%" style="width: 100%;">
                    <el-table-column
                        align="center"
                        type="index"
                        width="50">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="title"
                        label="标题"
                        min-width="240">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="typeName"
                        label="消息类型"
                        width="120">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="createDate"
                        label="创建日期"
                        width="120">
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        align="center"
                        label="操作"
                        width="240">
                        <template #default="scope">
                            <el-button size="small" type="success" :disabled="!(btOption.btNotepadDetail)"
                                @click="getNotepadDetail(scope.$index, scope.row)">详情</el-button>
                            <el-button size="small" :disabled="!(btOption.btUpdateNotepad)"
                                @click="updateNotepad(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="small" type="danger"  :disabled="!(btOption.btDeleteNotepad)"
                                @click="deleteNotepad(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </table-span>

        <el-dialog
            :title="notepadOption.title"
            v-model="notepadOption.isShow"
            @close="notepadDialogClose"
            :before-close="notepadDialogBeforeClose"
            @opened="notepadDialogOpened"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="720px">
            <el-form ref="notepadFormRef" :model="notepadForm" :rules="notepadRules" label-width="0px" size="default">
                <el-form-item label="" prop="title">
                    <el-input v-model="notepadForm.title" placeholder="请输入消息标题" :clearable="true" :disabled="notepadOption.isCanEdit"/>
                </el-form-item>
                <el-form-item label="" prop="createDate">
                    <el-date-picker v-model="notepadForm.createDate" type="date" placeholder="请选择日期" 
                    value-format="YYYY-MM-DD" size="default" :editable="false" :disabled="notepadOption.isCanEdit"/>
                </el-form-item>
            </el-form>
            
            <div style="border: 1px solid #ccc;">
                <div id="toolbar-container" style="border-bottom: 1px solid #ccc"></div>
                <div id="editor-container" :style="{'height': containerHeight + 'px', 'overflow-y': 'hidden'}"></div>
            </div>
            <template #footer v-if="notepadOption.type != '3'">
                <el-button size="default" @click="dialogCancel">取 消</el-button>
                <el-button size="default" type="primary" @click="notepadDialogSave">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script>
    import '@wangeditor/editor/dist/css/style.css'
    import TableSpan from '@/components/table-span.vue';
    import {tool} from "@/js/tool.js";
    import { ElMessage } from 'element-plus'
    import { createEditor, createToolbar } from '@wangeditor/editor/dist/index.js';

    const editorConfig = { 
        placeholder: '请输入内容...', 
        readOnly: false, 
        autoFocus: true
    }
    const toolbarConfig = {
        excludeKeys: ["uploadImage","uploadVideo","todo"]
    }

    export default {
        name: "notepad",
        data: function(){
            return {
                btOption: {
                    btSaveNotepad: null,
                    btUpdateNotepad: null,
                    btDeleteNotepad: null,
                    btNotepadDetail: null
                },
                tabelData: {
                    total: 0,
                    size: 10,
                    current: 1,
                    records: []
                },
                parentList: null,
                dateInterval: null,
                notepadCondition: {
                    startDate: null,
                    endDate: null,
                    type: null,
                    page: 1,
                    size: 10
                },
                notepadOption: {
                    title: "",
                    isShow: false,
                    type: "", // 1新增；2修改；3详情
                    isCanEdit: false,
                    selectRow: null
                },
                editor: {
                    editor: null,
                    toolbarConfig: {},
                    editorConfig: editorConfig,
                    mode: 'default',
                    html: ''
                },
                notepadForm: {
                    noteId: null,
                    title: '',
                    noteMessage: null,
                    createDate: '',
                    type: ''
                },
                containerHeight: 350,
                notepadRules: {
                    title : [
                        { required: true, message: '请输入消息标题', trigger: 'blur' }
                    ],
                    createDate : [
                        { required: true, message: '请输选择消息日期', trigger: 'blur' }
                    ],
                }
            }
        },
        methods: {
            searchData: function(){
                getNotepadList(this);
            },
            handleSizeChange: function(val){
                this.notepadCondition.size = val;
                this.notepadCondition.page = 1;
                getNotepadList(this);
            },
            handleCurrentChange: function(val){
                this.notepadCondition.page = val;
                getNotepadList(this);
            },
            btInsertNotepad: function(){
                this.notepadOption.type = "1";
                this.notepadOption.title = "新增消息";
                this.notepadOption.isShow = true;
                this.notepadOption.isCanEdit = false;
            },
            updateNotepad: function(index,row){
                this.notepadOption.type = "2";
                this.notepadOption.title = "编辑消息";
                this.notepadOption.isShow = true;
                this.notepadOption.isCanEdit = false;
                this.notepadOption.selectRow = row;
            },
            getNotepadDetail: function(index,row){
                this.notepadOption.type = "3";
                this.notepadOption.title = "消息详情";
                this.notepadOption.isShow = true;
                this.notepadOption.isCanEdit = true;
                this.notepadOption.selectRow = row;
            },
            dialogCancel: function(){
                dialogCloseTips(this);
            },
            deleteNotepad: function(index,row){
                const obj = this;
                const confirmMessage = "是否删除当前选择的消息";
                this.$confirm(confirmMessage).then(function(){
                    const param = {
                        noteId: row.noteId
                    };
                    deleteNotepad(obj,param);
                }).catch(function(){});
            },
            notepadDialogClose: function(){
                this.editor.editor.clear();//代办按钮清除不了？？

                this.notepadForm.noteId = null;
                this.notepadForm.title = null;
                this.notepadForm.noteMessage = '';
                this.notepadForm.type = null;
                this.notepadForm.createDate = null;
                this.notepadOption.selectRow = null;

                this.$refs["notepadFormRef"].clearValidate();

                const editor = this.editor.editor;
                if (editor != null) {
                    editor.destroy();
                }
            },
            notepadDialogBeforeClose: function(){
                dialogCloseTips(this);
            },
            notepadDialogOpened: function(){
                createEditorInit(this);

                if(this.notepadOption.type == '3'){
                    this.editor.editor.disable();
                    const param = {
                        noteId: this.notepadOption.selectRow.noteId
                    }
                    getNotepadById(this,param);
                }else{
                    this.editor.editor.enable();
                    if(this.notepadOption.type == '1'){
                        this.editor.editor.setHtml('');
                    }
                    const param = {
                        noteId: this.notepadOption.selectRow.noteId
                    }
                    getNotepadById(this,param);
                }
                
            },
            notepadDialogSave: function(){
                const obj = this;
                this.$refs["notepadFormRef"].validate(function(valid){
                    if (valid) {
                        obj.notepadForm.noteMessage = obj.editor.editor.getHtml();
                        if(obj.notepadOption.type == "1"){
                            notepadSave(obj);
                        }else{
                            notepadUpdate(obj);
                        }
                    } else {
                        return false;
                    }
                });
            }
        },
        mounted: function(){
            getSysdict(this);

            let date = this.$route.query.date;
            if(date){
                this.dateInterval = [date, date];
            }

            const menuId = [this.$route.query.menuId]
            const obj = this;
            new tool.getAuthorisedRequest(menuId, this.btOption, function(){
                getNotepadList(obj);
            });
        },
        components: {
            TableSpan
        },
        beforeDestroy: function() {
            const editor = this.editor.editor;
            if (editor == null) {
                return
            }
            editor.destroy();
        }
    }

    /**
     * 初始化编辑器
     */
    function createEditorInit(app){
        const editor = createEditor({
            selector: '#editor-container',
            config: editorConfig,
            mode: 'default'
        });
        app.editor.editor = editor;
        const toolbar = createToolbar({
            editor,
            selector: '#toolbar-container',
            config: toolbarConfig,
            mode: 'default', // or 'simple'
        });
    }

    /**
     * 获取消息信息列表
     * @param app app对象
     */
    function getNotepadList(app){
        let param = app.notepadCondition;
        if(app.dateInterval != null){
            param.startDate = app.dateInterval[0];
            param.endDate = app.dateInterval[1];
        }else{
            param.startDate = null;
            param.endDate = null;
        }
        const url = "/basic/notepad/getSelfNotepad";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.tabelData.records = data.data.records;
                app.tabelData.total = data.data.total;
                app.tabelData.size = data.data.size;
                app.tabelData.current = data.data.current;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 删除消息信息
     * @param app app对象
     */
    function deleteNotepad(app,param){
        const url = "/basic/notepad/deleteNotepad";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '消息删除成功',
                    type: 'success'
                });
                getNotepadList(app);
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 获取字典类型
     * @param app app对象
     */
    function getSysdict(app){
        const url = "/basic/dict/listByType";
        const param = ["notepad_type"]
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.parentList = data.data;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 根据消息的ID获取消息信息
     * @param app app对象
     * @param param 请求参数
     */
     function getNotepadById(app,param){
        app.editor.html = "";
        const url = "/basic/notepad/getNotepadById";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                const result = data.data;
                app.notepadForm.noteId = result.noteId;
                app.notepadForm.title = result.title;
                app.notepadForm.type = result.type;
                app.notepadForm.createDate = result.createDate;
                let message = (result.noteMessage != null)? result.noteMessage: '';
                app.editor.editor.setHtml(message);
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 保存消息信息
     * @param app app对象
     */
     function notepadSave(app){
        const url = "/basic/notepad/saveNotepad";
        const param = app.notepadForm;
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '消息信息保存成功',
                    type: 'success'
                });
                getNotepadList(app);
                app.notepadOption.isShow = false;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 更新消息信息
     * @param app app对象
     */
     function notepadUpdate(app){
        const url = "/basic/notepad/updateNotepad";
        const param = app.notepadForm;
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                ElMessage({
                    showClose: true,
                    message: '消息信息更新成功',
                    type: 'success'
                });
                getNotepadList(app);
                app.notepadOption.isShow = false;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 关闭dialog的提示信息
     * @param app
     */
     function dialogCloseTips(app) {
        if(app.notepadOption.type == "3"){
            app.notepadOption.isShow = false;
            return;
        }
        var confirmMessage = "";
        if(app.notepadOption.type == "1"){
            confirmMessage = "是否放弃新增消息信息？";
        }else{
            confirmMessage = "是否放弃修改消息信息？";
        }
        var obj = app;
        app.$confirm(confirmMessage).then(function(){
            obj.notepadOption.isShow = false;
        }).catch(function(){});
    }
</script>
<style>
    .notepad_manage_span{
        position: relative;
        display: flex;
        flex-direction: row;
        width: 100%;
        height: 100%;
        font-family: Microsoft YaHei,Heiti SC,tahoma,arial,Hiragino Sans GB,"\5B8B\4F53",sans-serif;
    }
    .search_item_span{
        max-width: 190px;
        height: auto;
        margin-top: 5px;
        margin-left: 10px;
    }
    .notepad_manage_span .search_item_fix_width{
        width: 370px;
        height: auto;
        margin-top: 5px;
        margin-left: 10px;
    }
</style>